const verify = require('jsonwebtoken')
const jwtConfig = require('../../config').JWT
const bcrypt = require('bcryptjs')
const CLIENT_SALT = '$2a$10$bNVbgiLkyewJT8IOaQY0Zu'

// 验证 JWT 有效性
const jwtVerify = (accessToken) => new Promise((resolve, reject) => {
  verify.verify(accessToken, jwtConfig.secret, function (err, decoded) {
    if (err) reject(err)
    resolve(decoded)
  })
})

// JWT 生成
const jwtGen = (data) => verify.sign({
  data: data
}, jwtConfig.secret, { expiresIn: jwtConfig.expires })

// 密码加密
const passwordBcrypt = async (password) => {
  const saltRounds = 10
  const salt = await bcrypt.genSalt(saltRounds)
  return await bcrypt.hash(password, salt)
}

// 密码对比
const passwordCompare = async (password, hash) => await bcrypt.compare(password, hash)

async function passwordClientBcrypt (password) {
  const hash = await bcrypt.hash(password, CLIENT_SALT)
  return hash.toString()
}

module.exports = {
  jwtGen,
  jwtVerify,
  passwordBcrypt,
  passwordCompare,
  passwordClientBcrypt
}
